// src/utils/amap-loader.js
let loadingPromise = null;

/**
 * 动态加载高德地图 JS API
 * @param {string} key 高德开放平台申请的 Key
 * @returns {Promise<void>}
 */
export function loadAMapScript(key) {
  // 如果已加载，直接返回
  if (window.AMap) {
    return Promise.resolve();
  }

  // 如果正在加载，返回同一个 Promise
  if (loadingPromise) {
    return loadingPromise;
  }

  loadingPromise = new Promise((resolve, reject) => {
    // 检查是否已存在 script 标签
    if (document.querySelector(`script[src*="webapi.amap.com"]`)) {
      return resolve();
    }

    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`;
    script.async = true;
    script.onload = () => resolve();
    script.onerror = () => {
      loadingPromise = null;
      reject(new Error('高德地图 SDK 加载失败，请检查网络或 Key 是否正确'));
    };
    document.head.appendChild(script);
  });

  return loadingPromise;
}